import { useEffect, useReducer } from 'react';
import { SchemaManageAPI } from '../type';
import _ from 'lodash';

interface IstateType {
  tableProps: SchemaManageAPI.ITableProps;
}

interface IactionType {
  type: 'screenColumns' | 'initTableProps' | 'clearInitTableProps';
  payload: Record<string, any>;
}

const screenProps = (props: Record<string, any>) => {
  const updateProps: any = {};
  if (props) {
    Object.keys(props)?.map((item) => {
      if (props?.[`${item}`]) {
        updateProps[`${item}`] = props?.[`${item}`];
      }
    });
  }

  return updateProps;
};

export const useTableProps = (props: SchemaManageAPI.ITableProps, switchOpt: Record<string, any>) => {
  const initialState = {
    tableProps: {},
  };

  const reducer = (state: IstateType, action: IactionType) => {
    switch (action.type) {
      case 'initTableProps': //初始化默认 赋值
        const updateProps = screenProps(action?.payload?.initProps);
        const showColumns: any = state?.tableProps?.columns;
        return {
          tableProps: {
            ...updateProps,
            columns: showColumns ? showColumns : updateProps?.columns,
          },
        };
      case 'screenColumns': //修改显示列保存赋值
        const updateColumns = _.cloneDeep(action?.payload?.columns);
        // const newTableProps = screenProps(state.tableProps);
        return {
          tableProps: {
            // ...newTableProps,
            ...state.tableProps,
            columns: updateColumns,
          },
        };
      case 'clearInitTableProps':
        return {
          tableProps: action?.payload,
        };
      default:
        throw new Error();
    }
  };

  const [state, dispatch] = useReducer(reducer, initialState);

  useEffect(() => {
    if (switchOpt?.key) {
      dispatch({
        type: 'clearInitTableProps',
        payload: {},
      });
    }
  }, [switchOpt?.key]);

  useEffect(() => {
    dispatch({
      type: 'initTableProps',
      payload: {
        initProps: props,
      },
    });
  }, [props]);

  return {
    tableProps: state.tableProps,
    dispatch,
  };
};
